package com.ajavaer.framework.common.tools;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 常用加密算法工具类
 */
public class EncryptTools {
    private static Logger log = LoggerFactory.getLogger(EncryptTools.class);

    private EncryptTools() {
    }

    /**
     * 用MD5算法进行加密
     *
     * @param str 需要加密的字符串
     * @return MD5加密后的结果
     */
    public static String md5(String str) {
        return encode(str, "MD5");
    }

    /**
     * 用SHA算法进行加密
     *
     * @param str 需要加密的字符串
     * @return SHA加密后的结果
     */
    public static String sha256(String str) {
        return encode(str, "SHA-256");
    }

    public static String createPassword(String str) {
        return md5(sha256(str));
    }

    /**
     * 生成 HMACSHA256
     *
     * @param data 待处理数据
     * @param key  密钥
     * @return 加密结果
     * @throws Exception
     */
    public static String hmacSHA256(String data, String key) {
        if (StringTools.isBlank(data, key)) {
            return null;
        }
        try {
            String method = "HmacSHA256";
            Mac sha256_HMAC = Mac.getInstance(method);
            SecretKeySpec secret_key = new SecretKeySpec(key.getBytes(StringTools.UTF8.name()), method);
            sha256_HMAC.init(secret_key);
            byte[] array = sha256_HMAC.doFinal(data.getBytes(StringTools.UTF8.name()));
            return byteArray2StringBuilder(array).toString();
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    private static String encode(String str, String method) {
        if (StringTools.isBlank(str)) {
            return null;
        }
        try {
            MessageDigest md = MessageDigest.getInstance(method);
            byte[] array = md.digest(str.getBytes());
            return byteArray2StringBuilder(array).toString();
        } catch (NoSuchAlgorithmException e) {
            log.error(e.getMessage(), e);
            return null;
        }
    }

    public static StringBuilder byteArray2StringBuilder(byte[] array) {
        StringBuilder sb = new StringBuilder();
        for (byte anArray : array) {
            sb.append(Integer.toHexString((anArray & 0xFF) | 0x100).substring(1, 3));
        }
        return sb;
    }
}